<script setup lang="ts">
import SubCategoryBread from "./components/SubCategoryBread.vue";
import SubCategoryFilter from "./components/SubCategoryFilter.vue";
import SubCategorySort from "./components/SubCategorySort.vue";
import GoodsList from "./components/GoodsList.vue";
import { useCategoryStore } from "@/stores/categoryStore";
import XtxInfiniteLoading from "../../components/XtxInfiniteLoading.vue";
import type { GoodsRequestParams } from "@/types/Goods";
import { onBeforeRouteUpdate } from "vue-router";

const categoryStore = useCategoryStore();
const { categoryGoods } = storeToRefs(categoryStore);
const { getCategoryGoods } = categoryStore;
// 获取路由信息
const route = useRoute();

// 用于存储筛选条件
let filterParams: Partial<GoodsRequestParams> = {};
// 用于存储筛选条件
let sortParams: Partial<GoodsRequestParams> = {};
// 用于存储页码数据
let pageParames = { page: 1, pageSize: 10 };
// 用于修改筛选条件状态
function updateFilterParams(params: Partial<GoodsRequestParams>) {
  filterParams = params;
}
// 用于修改排序条件
function updateSortParams(params: Partial<GoodsRequestParams>) {
  sortParams = params;
}

function getReqParams() {
  return { ...filterParams, ...sortParams, ...pageParames };
}
// 当筛选条件 排序条件发生变化以后重新获取商品列表
function sendRequest() {
  // 当筛选条件 排序条件发生变化 重置页码为1
  pageParames.page = 1;
  categoryGoods.value.status = "loading";
  // 获取二级分类商品列表
  getCategoryGoods(route.params.sub as string, getReqParams());
}

// 获取二级分类商品列表
getCategoryGoods(route.params.sub as string, getReqParams());

// 加载更多商品
function loadMore() {
  // 让页码+1累加页码
  pageParames.page = pageParames.page + 1;
  // 获取二级分类商品列表
  getCategoryGoods(route.params.sub as string, getReqParams());
}

// 监听路由变化
onBeforeRouteUpdate((to) => {
  // 重置筛选条件
  filterParams = {};
  // 重置排序条件
  sortParams = {};
  // 重置页码
  pageParames.page = 1;
  // 重置请求加载状态
  categoryGoods.value.status = "loading";
  // 获取二级分类商品列表
  getCategoryGoods(to.params.sub as string, getReqParams());
});
</script>

<template>
  <div class="container">
    <!-- 面包屑  -->
    <SubCategoryBread />
    <!-- 筛选条件 -->
    <SubCategoryFilter
      @onChanged="
        updateFilterParams($event);
        sendRequest();
      "
    />
    <div class="goods-list">
      <!-- 二级分类 排序组件 -->
      <SubCategorySort
        @onChanged="
          updateSortParams($event);
          sendRequest();
        "
      />
      <!-- 二级分类商品列表组件 -->
      <GoodsList :goodsList="categoryGoods.result.items" />
      <!-- 无限列表加载组件 -->
      <XtxInfiniteLoading
        :loading="categoryGoods.status === 'loading'"
        :finished="categoryGoods.status === 'finished'"
        @infinite="loadMore"
      />
    </div>
  </div>
</template>
<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
}
</style>
